package com.example.mq2.mqserver;


import com.example.mq2.common.BinaryTool;
import com.example.mq2.common.MqException;
import com.example.mq2.mqserver.core.BasicProperties;
import com.example.mq2.mqserver.core.Consumer;
import com.example.mq2.network.*;
import org.springframework.aop.interceptor.SimpleTraceInterceptor;

import javax.lang.model.element.NestingKind;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BrokerServer {

    private ServerSocket serverSocket = null;
    //此处用来表示一个客户端连接，key 表示 channelId
    private ConcurrentHashMap<String, Socket> sessions = new ConcurrentHashMap<>();
    private VirtualHost virtualHost = new VirtualHost("virtualHost1");
    private ExecutorService pool = null;
    private volatile boolean runnable = true;

    public BrokerServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
        pool = Executors.newCachedThreadPool();
    }

    public void start() {
        System.out.println("[BrokerServer] 启动！");
        while(runnable) {
            try {
                //阻塞等待和客户端建立连接，拿到客户端的连接
                Socket clientSocket = serverSocket.accept();
                pool.submit(() -> {
                    //每一个连接都使用线程池分配一个线程来处理
                    processConnection(clientSocket);
                });
            } catch (SocketException e) {
                System.out.println("[BrokerServer] 客户端关闭连接！");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 关闭服务器，提供给测试类使用
     */
    public void stop() throws IOException {
        System.out.println("[BrokerServer] 停止！");
        runnable = false;
        pool.shutdown();
        serverSocket.close();
    }

    private void processConnection(Socket clientSocket) {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
                while(true) {
                    //1.读取请求并解析
                    Request request = readRequest(dataInputStream);
                    //2.根据请求计算响应
                    Response response = process(request, clientSocket);
                    //3.返回响应给客户端
                    writeResponse(response, dataOutputStream);
                }
            }
        } catch (SocketException e) {
            System.out.println("[BrokerServer] 服务器断开连接！");
        } catch (IOException | MqException e) {
            throw new RuntimeException(e);
        } finally {
            //释放资源
            try {
                clientSocket.close();
                //删除所有socket有关的连接
                clearSocket(clientSocket);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 清除所有有关的 socket
     */
    private void clearSocket(Socket clientSocket) {
        List<String> toDeleteKey = new ArrayList<>();
        for(Map.Entry<String, Socket> entry: sessions.entrySet()) {
            if(entry.getValue() == clientSocket) {
                toDeleteKey.add(entry.getKey());
            }
        }
        for(String channelId : toDeleteKey) {
            sessions.remove(channelId);
        }
    }

    /**
     * 将请求写会客户端
     * @param response
     * @param dataOutputStream
     */
    private void writeResponse(Response response, DataOutputStream dataOutputStream) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        dataOutputStream.flush();
        System.out.println("[Response] type=" + response.getType() + ", length=" + response.getLength());
    }

    /**
     * 根据请求计算响应
     * @return
     */
    private Response process(Request request, Socket clientSocket) throws MqException, IOException {
        //对请求进行一个初步解析
        BasicRequest basicRequest = (BasicRequest) BinaryTool.fromBytes(request.getPayload());
        //根据 type 执行对应的响应方法
        boolean ok = true;
        if(request.getType() == 0x1) {
            sessions.put(basicRequest.getChannelId(), clientSocket);
            System.out.println("[BrokerServer] Channel 创建完成！channelId=" + basicRequest.getChannelId());
        } else if(request.getType() == 0x2) {
            sessions.remove(basicRequest.getChannelId());
            System.out.println("[BrokerServer] Channel 销毁完成！channelId=" + basicRequest.getChannelId());
        } else if(request.getType() == 0x3) {
            ExchangeDeclareArguments exchangeDeclareArguments = (ExchangeDeclareArguments) basicRequest;
            ok = virtualHost.exchangeDeclare(exchangeDeclareArguments.getName(), exchangeDeclareArguments.getType(),
                    exchangeDeclareArguments.isDurable(), exchangeDeclareArguments.isAutoDelete(), exchangeDeclareArguments.getArguments());
        } else if(request.getType() == 0x4) {
            ExchangeDeleteArguments exchangeDeleteArguments = (ExchangeDeleteArguments) basicRequest;
            ok = virtualHost.exchangeDelete(exchangeDeleteArguments.getName());
        } else if(request.getType() == 0x5) {
            QueueDeclareArguments queueDeclareArguments = (QueueDeclareArguments) basicRequest;
            ok = virtualHost.queueDeclare(queueDeclareArguments.getName(), queueDeclareArguments.isDurable(),
                    queueDeclareArguments.isExclusive(), queueDeclareArguments.isAutoDelete(), queueDeclareArguments.getArguments());
        } else if(request.getType() == 0x6) {
            QueueDeleteArguments queueDeleteArguments = (QueueDeleteArguments) basicRequest;
            ok = virtualHost.queueDelete(queueDeleteArguments.getName());
        } else if(request.getType() == 0x7) {
            QueueBindArguments queueBindArguments = (QueueBindArguments) basicRequest;
            ok = virtualHost.queueBind(queueBindArguments.getExchangeName(), queueBindArguments.getQueueName(),
                    queueBindArguments.getBindingKey());
        } else if(request.getType() == 0x8) {
            QueueUnBindingArguments queueUnBindingArguments = (QueueUnBindingArguments) basicRequest;
            ok = virtualHost.queueUnBind(queueUnBindingArguments.getExchangeName(), queueUnBindingArguments.getQueueName());
        } else if(request.getType() == 0x9) {
            BasicPublishArguments basicPublishArguments = (BasicPublishArguments) basicRequest;
            ok = virtualHost.basicPublish(basicPublishArguments.getExchangeName(), basicPublishArguments.getRoutingKey(),
                    basicPublishArguments.getBasicProperties(), basicPublishArguments.getBody());
        } else if(request.getType() == 0xa) {
            BasicConsumerArguments basicConsumer = (BasicConsumerArguments) basicRequest;
            ok = virtualHost.basicConsume(basicConsumer.getConsumerTag(), basicConsumer.getQueueName(), basicConsumer.getAutoAck(),
                    new Consumer() {
                        @Override
                        public void handlerDeliver(String consumerTag, BasicProperties basicProperties, byte[] body) throws IOException {
                            //这里后端会将以上参数都计算出相应的值，这里我们只需要返回 0xc 的响应，让客户端执行拿到消息后具体要执行的动作
                            MessageCallbackArguments messageCallbackArguments = new MessageCallbackArguments();
                            messageCallbackArguments.setRid("");//这里是一个让客户端执行的消息回调，不需要 rid 对应
                            messageCallbackArguments.setChannelId(consumerTag);   //这里传 consumerTag 就可以(实际上就是一个 channelId)
                            messageCallbackArguments.setConsumerTag(consumerTag); //
                            messageCallbackArguments.setBasicProperties(basicProperties);
                            messageCallbackArguments.setBody(body);
                            byte[] payload = BinaryTool.toBytes(messageCallbackArguments);

                            Response response = new Response();
                            response.setType(0xc);
                            response.setLength(payload.length);
                            response.setPayload(payload);
                            //将响应写会客户端
                            DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                            writeResponse(response, dataOutputStream);
                        }
                    });
        } else if(request.getType() == 0xb) {
            BasicAckArguments basicAckArguments = (BasicAckArguments) basicRequest;
            ok = virtualHost.basicAck(basicAckArguments.getQueueName(), basicAckArguments.getMessageId());
        } else {
            throw new MqException("[BrokerServer] 请求类型不存在！type=" + request.getType());
        }

        //构造响应
        BasicResponse basicResponse = new BasicResponse();
        basicResponse.setRid(basicRequest.getRid());
        basicResponse.setChannelId(basicRequest.getChannelId());
        basicResponse.setOk(ok);
        byte[] payload = BinaryTool.toBytes(basicResponse);

        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);
        return response;
    }

    /**
     * 读取请求
     * @param dataInputStream
     * @return
     * @throws IOException
     */
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        int type = dataInputStream.readInt();
        int length = dataInputStream.readInt();
        byte[] payload = new byte[length];
        int n = dataInputStream.read(payload);
        if(n != length) {
            System.out.println("[BrokerServer] 读取请求格式出错！expectedSize=" + length + ", actualSize=" + n);
        }
        Request request = new Request();
        request.setType(type);
        request.setLength(length);
        request.setPayload(payload);
        System.out.println("[Request] type=" + request.getType() + ", length=" + request.getLength());
        return request;
    }

}
